﻿using Protocol.Code;
using Script.Framework;
using Script.UI.Msg;
using UnityEngine;
using UnityEngine.UI;

namespace Script.UI._1.Main
{
    public class CreatePanel : UIBase
    {
        private void Awake()
        {
            Bind(UIEvent.CREATE_PANEL_ACTIVE);
        }

        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case UIEvent.CREATE_PANEL_ACTIVE:
                    SetPanelActive((bool) message);
                    gameObject.SetActive((bool) message);
                    break;
            }
        }

        private InputField inputName;
        private Button btnCreate;

        private PromptMsg promptMsg;
        private SocketMsg socketMsg;

        // Start is called before the first frame update
        void Start()
        {
            // 获取对象
            inputName = transform.Find("inputName").GetComponent<InputField>();
            btnCreate = transform.Find("Btn_Create").GetComponent<Button>();

            // 创建对象
            promptMsg = new PromptMsg();
            socketMsg = new SocketMsg();


            // 注册事件
            btnCreate.onClick.AddListener(CreateClick);
        }


        public override void OnDestroy()
        {
            base.OnDestroy();
            btnCreate.onClick.RemoveListener(CreateClick);
        }

        private void CreateClick()
        {
            if (string.IsNullOrEmpty(inputName.text))
            {
                // 非法输入
                promptMsg.Change("请输入一个昵称", Color.red);
                Dispatch(AreaCode.UI, UIEvent.PROMPT_MSG, promptMsg);
                return;
            }

            // 自身处理： 长度 字符限制

            //发送请求
            socketMsg.Change(OpCode.USER, UserCode.CREAT_CREQ, inputName.text);
            Dispatch(AreaCode.NET, 0, socketMsg);
        }
    }
}